package com.LJ.handler;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.LJ.util.Context;
import com.weixin.exception.WeiXinLoginException;
import com.weixin.exception.WeixinException;
import com.weixin.util.ErrorCode;
import com.weixin.util.WeiXinUtil;

/**
 * 项目引导入口(目标获取用户openid)
 * 
 * @author huangwenbin
 *
 */
@Controller
@RequestMapping(value = "/guide")
public class GuideHandler {

	private static Logger logger = LogManager.getLogger();

	/**
	 * 微信接入（获取openid）
	 * 
	 * @param code
	 * @param request
	 * @return
	 * @return
	 * @throws WeixinException
	 * @throws IOException
	 * @throws WeiXinLoginException
	 */
	@RequestMapping(value = "/join")
	public String wechatJoin(@RequestParam(value = "code") String code, HttpServletRequest request)
			throws WeixinException, IOException {

		// 这里判断用户是否是第一次登录，还是通过返回返回到这个链接
		if (request.getSession().getAttribute(Context.OPENID) == null) {
			// 获取用户openid的
			// if (code == null || code.isEmpty()) {
			// throw new WeixinException(ErrorCode.NoWechatCode);
			// }
			//
			// // 获取用户openid , access_token
			// String openid = null;
			// try {
			// Map<String, String> result =
			// WeiXinUtil.getSpecialAccessTokenForUserInfoByCode(code);
			// System.out.println("result :" + result);
			// openid = result.get("openid");
			// } catch (IOException e) {
			// logger.debug(e);
			// openid = null;
			// }
			//
			// if (openid == null || openid.isEmpty()) {
			// throw new WeixinException(ErrorCode.NoOpenid);
			// }

			// 模拟黄文彬微信号
			String openid = "ovinCt2YPO-xE5bZs65uV7TyeeME";

			// 2. 将用户openid存储到session中
			request.getSession().setAttribute(Context.OPENID, openid);
		}

		return "redirect:/wechat/signin/signin";
	}
}